<?php
/**
 * 
 * Attempts to find and replace all occurances of an old URL in a wordpress database
 * @author piers@uknetweb.com
 * 
 */
include ('wp-config.php');
require_once(ABSPATH . 'wp-includes/wp-db.php');
$messages = array();
$wpdb = new wpdb(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
$url = $wpdb->get_row('SELECT option_value FROM ' . $table_prefix . 'options WHERE option_name = "siteurl"')->option_value;
$siteName = $wpdb->get_row('SELECT option_value FROM ' . $table_prefix . 'options WHERE option_name = "blogname"')->option_value;
foreach ($wpdb->get_col("SHOW TABLES", 0) as $table) {
	if (strstr($table, $table_prefix)) {
		$tables[] = $table;
	};
};
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
	if ($_POST['selfDestruct']) {
		if (@unlink(__FILE__)) {
			die('File Deleted');
		} else {
			die('Couldn\'t delete file, you\'ll have to remove it yourself, sorry.');
		};
	};
	
	if (strlen($_POST['newUrl']) > 0) {
		$newUrl = addslashes($_POST['newUrl']);
	} else {
		die('No new URL entered');
	};
	
	foreach ($tables as $table) {
		$columns = $wpdb->get_results('DESC ' . $table);
		foreach ($columns as $column) {
			$field = $column->Field;
			$wpdb->query('UPDATE ' . $table . ' SET ' . $field . ' = REPLACE(' . $field . ',"' . $url . '","' . $newUrl . '")');
			if ($wpdb->rows_affected > 0) {
				$style = 'green';
			} else {
				$style = '';
			};
			
			$messages[] = '<span class="' . $style . '">Found ' . $wpdb->rows_affected . ' matches in <b>' . $table . '->' . $field . '</b></span>';
		};
	};
};
?>
<html>
	<head>
		<meta name="ROBOTS" content="NOINDEX, NOFOLLOW">
		<title>Worpress Migrator for <?php echo $siteName ?></title>
		<style type="text/css">
			*{font-family: Georgia}
			#main{width:800px;margin:auto;}
			.green{color:#006505}
			#selfDestruct,#selfDestruct input{background-color:#fee;color:#f00;text-align:center;margin:20px}
		</style>
	</head>
	<body>
		<div id="main">
			<h1>Wordpress Migrator v0.1</h1>
			<?php foreach ($messages as $line): ?>
			<?php echo $line; ?><br/>
			<?php endforeach; ?>
			<?php if (count($messages) == 0): ?>
			<form method="post">
				<fieldset>
					<p>Current URL : <b><?php echo $url ?></b></p>
					<p>New URL : <input name="newUrl" type="text"/></p>
					<input type="submit"/>
				</fieldset>
			</form>
			<?php endif ?>
			<form id="selfDestruct" method="post">
				<input type="submit" value="Self Destruct" name="selfDestruct" onclick="return(confirm('This will attempt to delete this script, you sure?'))"/>
			</form>
		</div>
	</body>
</html>